package cn.lijiajia3515.cairo.system.modules.imgproxy;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Controller
@RequestMapping("/api/imgproxy")
public class ImgproxyController {
	private final ImgproxyService imgProxyService;

	public ImgproxyController(ImgproxyService imgProxyService) {
		this.imgProxyService = imgProxyService;
	}

	@GetMapping("/access")
	public ModelAndView access(HttpServletRequest request) throws Exception {
		final Map<String, String[]> parameterMap = request.getParameterMap();
		final Map<String, String> params = parameterMap.keySet()
			.stream()
			.filter(x -> x.startsWith("imgproxy_"))
			.collect(Collectors.toMap(x -> x.replaceFirst("imgproxy_", ""), v -> {
				final String[] strings = parameterMap.get(v);
				return strings == null || strings.length == 0 ? "" : strings[0];
			}));
		String sourceUrl = Stream.of(parameterMap.getOrDefault("source_url", new String[]{"default.png"})).findFirst().orElse("default.png");

		return new ModelAndView(new RedirectView(imgProxyService.getSingedUrl(sourceUrl, params)));
	}
}
